﻿Imports sonicERPDAL
Imports sonicERPinfo
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.SoapFault
Imports System.Xml.Serialization



Partial Public Class Cadastronivel
    Inherits Paginabase
   
    Shared codigo As Integer
    Dim util As New Util
    Dim lista As New List(Of String)
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Try
                getmenutreeview()
                Dim paginavisivel As Boolean
                paginavisivel = util.validarpagina(1)
                If Not paginavisivel Then
                    FormsAuthentication.SignOut()
                    Response.Redirect(ResolveUrl("~/Login.aspx"))
                End If

                pnl1.Visible = False
                codigo = Convert.ToInt32(Request.QueryString("id"))
                txtnivel.Text = Convert.ToString(Request.QueryString("nivel"))
                ' menus()
                If codigo <> 0 Then
                    'For Each item As ListItem In ckblist.Items
                    '    menu.idnivel = codigo
                    '    menu.idmenu = item.Value
                    '    menudal.lista1(menu)
                    '    item.Selected = menu.visible
                    'Next

                    sessaousuario.menu.idnivel = codigo
                    Dim dt As DataTable = dal.menu.getmenvisible(sessaousuario.menu)

                    For dtelemento = 0 To dt.Rows.Count - 1
                        For index = 0 To trvmenu.Nodes.Count - 1
                            Dim totalchildnodes As Integer = trvmenu.Nodes(index).ChildNodes.Count
                            For elemento = 0 To totalchildnodes - 1
                                trvmenu.Nodes(index).ChildNodes(elemento).Checked = Convert.ToBoolean(dt.Rows(dtelemento).Item(0).ToString())
                                dtelemento += 1
                            Next
                        Next
                    Next


                    For index = 0 To trvmenu.Nodes.Count - 1
                        Dim totalchildnodes As Integer = trvmenu.Nodes(index).ChildNodes.Count
                        For elemento = 0 To totalchildnodes - 1
                            If trvmenu.Nodes(index).ChildNodes(elemento).Checked Then
                                trvmenu.Nodes(index).Checked = True
                                elemento += 1
                            End If
                        Next
                    Next


                End If

            Catch ex As Exception
                pnl1.Visible = True
                lblerro.Text = ex.Message
            End Try
        End If


    End Sub


    Protected Sub imgvoltar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgvoltar.Click
        Try
            pnl1.Visible = False
            imgintexclamacao.ImageUrl = "~/img/warning_blue.png"
            Dim url As String = String.Format("~/adm/nivelLista.aspx")
            Response.Redirect(ResolveUrl(url))
        Catch ex As Exception
            pnl1.Visible = True
            lblerro.Text = ex.Message
        End Try
    End Sub

    Protected Sub imgexcluir_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgexcluir.Click
        Try
            pnl1.Visible = False
            imgintexclamacao.ImageUrl = "~/img/warning_blue.png"
            If codigo = 0 Then
                Throw New Exception("Não Existe Cadastro Para Exclusão")
            End If

            util.getusuarios(lista)

            sessaousuario.nivelusuario.id = codigo
            sessaousuario.nivelusuario.idusuario = lista.Item(0).ToString()

            txtnivel.Text = txtnivel.Text.Trim()
            sessaousuario.nivelusuario.nivel = Convert.ToString(txtnivel.Text)
            sessaousuario.nivelusuario.dt_cadastro = Now
            dal.nivelusuario.excluir(sessaousuario.nivelusuario)

            For index = 0 To trvmenu.Nodes.Count - 1
                For Each item As TreeNode In trvmenu.Nodes(index).ChildNodes
                    Dim valor As String = item.Value
                    Dim idmenu As String = valor.Substring(0, 1)
                    Dim submenu As String = valor.Substring(8, 1)
                    sessaousuario.menu = New Menu
                    sessaousuario.menu.idmenu = Convert.ToInt32(idmenu)
                    sessaousuario.menu.idnivel = codigo
                    sessaousuario.menu.menu = item.Text
                    sessaousuario.nivelusuario.menus.Add(sessaousuario.menu)
                    dal.menu.delete1(sessaousuario.menu)
                Next
            Next
            sessaousuario.Logs.nometabela = "nivelUsuario"
            sessaousuario.Logs.idtabela =   sessaousuario.nivelusuario.id 
            sessaousuario.nivelusuario.id = sessaousuario.Logs.idtabela
            sessaousuario.nivelusuario.tipocomando = "DELETE"
            sessaousuario.Logs.tipocomando = sessaousuario.nivelusuario.tipocomando
            sessaousuario.Logs.xmltabela = util.gerarxml(sessaousuario.nivelusuario)
            dal.logs.delete(sessaousuario)
            codigo = 0
            limpar()
            Dim url As String = "~/adm/Padrao.aspx?erro1=" & Server.HtmlDecode("Cadastro Excluido Com Sucesso")
            Response.Redirect(ResolveUrl(url))
        Catch ex As Exception
            pnl1.Visible = True
            lblerro.Text = ex.Message
        End Try
    End Sub

    Protected Sub imggravar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imggravar.Click
        Try
            Dim idmenu As String
            Dim submenu As String
            pnl1.Visible = False
            imgintexclamacao.ImageUrl = "~/img/warning_blue.png"
            If String.IsNullOrEmpty(txtnivel.Text) Then
                txtnivel.Focus()
                codigo = 0
                Throw New Exception("Digite o Nivel do Usuario")
                Return
            End If
            Dim i As Boolean

            For index = 0 To trvmenu.Nodes.Count - 1
                For Each item As TreeNode In trvmenu.Nodes(index).ChildNodes
                    If item.Checked = True Then
                        i = item.Checked
                        index = trvmenu.Nodes.Count - 1
                        Exit For
                    End If
                    i = item.Checked
                Next
            Next


            If i = False Then
                Throw New Exception("Selecione Pelos Menos Um Menu Para o Nivel    " & txtnivel.Text & "       Ter Acesso")
            End If
            If codigo = 0 Then
                util.getusuarios(lista)
                sessaousuario.nivelusuario.idusuario = Convert.ToInt32(lista.Item(0).ToString())
                '  modelo.idusuario = Request.Cookies("usuario")("id")
                txtnivel.Text = txtnivel.Text.Trim()
                sessaousuario.nivelusuario.nivel = Convert.ToString(txtnivel.Text.ToUpper)
                dal.nivelusuario.insert(sessaousuario.nivelusuario)
                For index = 0 To trvmenu.Nodes.Count - 1

                    For Each item As TreeNode In trvmenu.Nodes(index).ChildNodes
                        Dim valor As String = item.Value
                        If valor.Length = 9 Then
                            idmenu = valor.Substring(0, 1)
                            submenu = valor.Substring(8, 1)
                        Else
                            idmenu = valor.Substring(0, 2)
                            submenu = valor.Substring(9, 1)
                        End If
                        sessaousuario.menu = New Menu
                        sessaousuario.menu.idmenu = Convert.ToInt32(idmenu)
                        sessaousuario.menu.visible = item.Checked
                        sessaousuario.menu.idgrupo = Convert.ToInt32(submenu)
                        sessaousuario.menu.menu = item.Text
                        sessaousuario.nivelusuario.menus.Add(sessaousuario.menu)
                        dal.menu.insert1(sessaousuario.menu)

                    Next

                Next
                sessaousuario.Logs.nometabela = "nivelUsuario"
                sessaousuario.Logs.idtabela = dal.logs.getlista(sessaousuario, New Object)
                sessaousuario.nivelusuario.id = sessaousuario.Logs.idtabela
                sessaousuario.nivelusuario.tipocomando = "INSERT"
                sessaousuario.Logs.tipocomando = sessaousuario.nivelusuario.tipocomando

                sessaousuario.Logs.xmltabela = util.gerarxml(sessaousuario.nivelusuario)

                dal.logs.insert(sessaousuario)
                limpar()
                Dim url As String = "~/adm/Padrao.aspx?erro2=" & Server.HtmlDecode("Cadastro Efetuado com Sucesso")
                Response.Redirect(ResolveUrl(url))
            Else
                util.getusuarios(lista)
                sessaousuario.nivelusuario.id = codigo
                sessaousuario.nivelusuario.idusuario = Convert.ToInt32(lista.Item(0).ToString)

                txtnivel.Text = txtnivel.Text.Trim()
                sessaousuario.nivelusuario.nivel = Convert.ToString(txtnivel.Text.ToUpper)
                sessaousuario.nivelusuario.dt_cadastro = Now
                dal.nivelusuario.update(sessaousuario.nivelusuario)
               


                'For Each item As ListItem In ckblist.Items
                '    menu.idmenu = item.Value
                '    menu.visible = item.Selected
                '    menu.idnivel = codigo
                '    menudal.update(menu)
                'Next
                For index = 0 To trvmenu.Nodes.Count - 1
                    For Each item As TreeNode In trvmenu.Nodes(index).ChildNodes
                        Dim valor As String = item.Value

                        If valor.Length = 9 Then
                            idmenu = valor.Substring(0, 1)
                            submenu = valor.Substring(8, 1)
                        Else
                            idmenu = valor.Substring(0, 2)
                            submenu = valor.Substring(9, 1)
                        End If
                        sessaousuario.menu = New Menu
                        sessaousuario.menu.idmenu = Convert.ToInt32(idmenu)
                        sessaousuario.menu.visible = item.Checked
                        sessaousuario.menu.idnivel = codigo
                        sessaousuario.menu.menu = item.Text
                        sessaousuario.nivelusuario.menus.Add(sessaousuario.menu)
                        dal.menu.update1(sessaousuario.menu)

                    Next
                Next
                sessaousuario.Logs.nometabela = "nivelUsuario"
                sessaousuario.Logs.idtabela = sessaousuario.nivelusuario.id
                sessaousuario.nivelusuario.id = sessaousuario.Logs.idtabela
                sessaousuario.nivelusuario.tipocomando = "UPDATE"
                sessaousuario.Logs.tipocomando = sessaousuario.nivelusuario.tipocomando
                sessaousuario.Logs.xmltabela = util.gerarxml(sessaousuario.nivelusuario)
                dal.logs.update(sessaousuario)
                codigo = 0
                limpar()
                Dim url As String = "~/adm/Padrao.aspx?erro3=" & Server.HtmlDecode("Cadastro Alterado com Sucesso")
                Response.Redirect(ResolveUrl(url))
            End If
        Catch ex As Exception
            pnl1.Visible = True
            lblerro.Text = ex.Message
        End Try
    End Sub
    Public Sub limpar()
        txtnivel.Text = ""
    End Sub

  
    'Public Sub menus()
    '    Dim dal As New menuDAL

    '    ckblist.DataSource = dal.lista()
    '    ckblist.DataValueField = "id"
    '    ckblist.DataTextField = "menu"
    '    ckblist.DataBind()


    'End Sub

    Public Sub getmenutreeview()
        Dim dal As New menuDAL
        Dim entidade As New Menu

        Dim dtmenu As DataTable = dal.getmenu1(entidade)
        Dim dtsubmenu As DataTable = dal.getmenugrupo(entidade)

        For Each menu As DataRow In dtmenu.Rows
            Dim trmenu As New TreeNode(menu.Item(1).ToString(), menu.Item(0).ToString())

            For Each submenu As DataRow In dtsubmenu.Rows
                If menu.Item(0).ToString() = submenu.Item(2).ToString() Then
                    Dim trsubmenu As New TreeNode(submenu.Item(1).ToString(), submenu.Item(0).ToString() & "submenu" & submenu.Item(2).ToString())
                    trmenu.ChildNodes.Add(trsubmenu)

                End If
            Next
            trvmenu.Nodes.Add(trmenu)

        Next


    End Sub
   
   

    Protected Sub trvmenu_SelectedNodeChanged(ByVal sender As Object, ByVal e As EventArgs) Handles trvmenu.SelectedNodeChanged
     
    End Sub

    Protected Sub trvmenu_TreeNodeCheckChanged(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles trvmenu.TreeNodeCheckChanged
        For Each item As TreeNode In e.Node.ChildNodes
            item.Checked = e.Node.Checked
            Dim s As String = item.Text
        Next

        

        For Each item As TreeNode In trvmenu.Nodes
            Dim submenu As String = Nothing
            Dim valor As String = trvmenu.SelectedValue
            If valor.Length > 1 Then
                submenu = valor.Substring(8, 1)
            End If
            If item.Value = submenu Then
                item.Checked = e.Node.Checked

            End If

        Next
    End Sub


    Protected Sub imgnovo_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgnovo.Click
        Dim url As String = String.Format("~/adm/Cadastronivel.aspx")
        Response.Redirect(ResolveUrl(url))
    End Sub
End Class